#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:set sts=4:tabstop=4:expandtab:shiftwidth=4:
# EasyUbuntu - Install commonly requested apps on your (k/X)ubuntu box 
# Copyright (C) 2006 EasyUbuntu team
# https://launchpad.net/products/easyubuntu
# http://easyubuntu.freecontrib.org
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
# 
import os
import sys
import subprocess

def aptcheck():
    """
    Check if any apt processes are running
    """
    p = os.popen("ps -U root -o comm")
    running = False
    pslist = p.readlines()
    p.close()
    for process in pslist:
        if process.strip() in ["dpkg", "apt-get","synaptic","update-manager", "adept", "adept-notifier"]:
            running = True
            break
    return running

def codename():
    """
    Get system codename, can be warty/hoary/breezy/dapper
    """
    p = os.popen("lsb_release -c")
    try:
        codename = p.readline().strip()
        tokens = codename.split("\t")
    finally:
        p.close()
    return tokens[-1].lower()

def architecture():
    """
    Detect whether the architecture is x86/ppc/amd64 
    """
    arch = os.uname()[-1]
    if arch in ('ppc', 'ppc64'):
        arch = 'powerpc'
    elif arch =='x86_64':
        arch = 'amd64'
    elif arch in ('i386','i686','i586','k7'):
        arch = 'x86'
    return arch

def de():
    """
    Detect whether the system has gnome or kde (python) libraries or both
    """
    gnome, kde = False, False
    try:
        import qt
        kde = True
    except ImportError:
        pass

    try:
        import gtk, gtk.glade
        gnome = True
    except ImportError:
        pass
    if gnome and kde:
        p = os.popen("ps -e -o comm")
        pslist = p.readlines()
        p.close()
        for process in pslist:
            if process.strip() == 'gnome-session':
                return 'gnome'
        return 'kde'
    elif gnome:
        return "gnome"
    elif kde:
        return "kde"
    else:
        print 'Error: No suitable frontend found.'
        sys.exit(1)

def system_sanity_check():
    apt = subprocess.Popen("apt-get -f install", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    apt.wait()
    errors = apt.stderr.read()
    if errors:
        print "System sanity check: Failed!"
        print "Errors: "
        print "-"*8
        print errors
        print "EasyUbuntu is now trying to run 'dpkg --configure -a'" 
        
        dpkg = subprocess.Popen("dpkg --configure -a", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
        dpkg.wait()
        errors = dpkg.stderr.read()
        if errors:
            print "System sanity check: Failed!"
            print "Errors: "
            print "-"*8
            print errors
            return False
    
    # TODO: might want to check to see if *buntu-desktop package is installed.  if not, install. we don't want to cause broken upgrades!
    print "System sanity check: PASSED!"
    return True 

def replace(confdir):
    """
    Create a localised sources.list, with universe and multiverse
    """
    try:
        os.remove(os.path.join(confdir,'sources.list'))
    except OSError:
        pass
    if not os.path.exists(confdir): 
        os.mkdir(confdir, 0777)

    sourcelist = open('/etc/apt/sources.list', 'r')
    targetlist = open(os.path.join(confdir, 'sources.list'),'w')

    for line in sourcelist:
        """
        deb http://archive.ubuntu.com/ubuntu/ dapper main restricted 
        """
        if not "cdrom" in line and line.startswith("deb ") and codename()+" " in line:
            repos_URI = line.split()[1]
            repos_string = "deb %s %s main restricted universe multiverse\n" % (repos_URI, codename())
            targetlist.write(repos_string)
            break
    
    sourcelist.close()

    arch = architecture()
    
    if arch == 'powerpc' or arch == 'x86':
        targetlist.write("deb http://packages.freecontrib.org/plf/ %s free non-free\n" % codename())
    elif arch == 'amd64':
        print "amd64 detected"
    else:
        print 'No supported architectures found, please contact authors in #easyubuntu on irc.freenode.net for help'

    targetlist.write("# The above lines were generated automatically by EasyUbuntu 3.02 Release\n") 
    targetlist.write("# The rest of your sources.list follows\n\n\n")
    
    sourcelist = open('/etc/apt/sources.list', 'r')
    for line in sourcelist:
        try:
            if "cdrom" in line or (line.startswith("deb ") and repos_URI == line.split()[1]):
                if ('%s-updates' % codename()) not in line:
                    targetlist.write(line.replace("deb","#deb"))
                # Comment out cdrom line
                # Comment out the line with the main repos
                # to prevent multiple repos error
            else:
                targetlist.write(line)
        except UnboundLocalError:
            print """
Your sources.list does not match your system configuration.
Either you have changed your sources.list or an system
upgrade has failed. EasyUbuntu will not run unless these are fixed!"""
            sys.exit(1)
    
    sourcelist.close()
    targetlist.close()
    unduplicate(os.path.join(confdir, 'sources.list'))
    #os.popen("chown -R "+os.getlogin()+":"+os.getlogin()+" "+confdir)
    user = os.getenv('SUDO_USER')
    cmd = "chown -R " + user + ":" + user + " " + confdir
    subprocess.Popen(cmd, shell=True)

def unduplicate(sourcefile):
    """
    Removes the duplicate lines in the sources.list
    """
    source  = open(sourcefile, "r")
    target = [ ]

    for line in source:
        if line not in target:
            target.append(line)
    source.close()

    targetfile = open(sourcefile,"w")
    for line in target:
        targetfile.write(line)

    targetfile.close()

if __name__ == "__main__":
    print "You are running a", codename().upper()
    print "system on", architecture().upper(), "architecture"
    #print de().upper(), "available"
    confdir = os.path.abspath('./conf')
    replace(confdir)
    print "Localised sources.list generated in", confdir
